/**
 * 
 */
package us.gaaoc.framework.webapp.phaselisteners;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import us.gaaoc.framework.model.Person;

/**
 * @author robinsom
 * 
 */
public class SecurityPhaseListener implements PhaseListener {

	/** Generated Serial Version UID */
	private static final long serialVersionUID = 4364543332906164108L;
	/**
	 * Property
	 */
	private static final Logger LOG = Logger.getLogger(SecurityPhaseListener.class);

	/**
	 * COnstructor
	 */
	public SecurityPhaseListener() {
	}

	public void beforePhase(PhaseEvent phaseEvent) {
	}

	public void afterPhase(PhaseEvent phaseEvent) {		

		FacesContext facesContext = FacesContext.getCurrentInstance();

		if (facesContext.getViewRoot() != null) {
			String viewId = facesContext.getViewRoot().getViewId();
			// Any Page under the Secure directory
			if (viewId.matches("/secure/.*")) {
				//Get the Person who logged in
				Person person = (Person) facesContext.getExternalContext().getSessionMap().get("person");
				//If person can't find then redirect to the Log In page
				if (person == null) {
					LOG.debug("Person is not logged in......");
					try {
						HttpSession httpSession = (HttpSession) facesContext.getExternalContext().getSession(false);
						httpSession.invalidate();
						//facesContext.getExternalContext().redirect("../../index.html");
						facesContext.getExternalContext().redirect(facesContext.getExternalContext().getRequestContextPath() + "/index.html");
					} catch (IOException e) {
						e.printStackTrace();
						throw new FacesException(e);
					}
				}
			}
		}
	}

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
}